<!DOCTYPE html>
<html>

<head>
    <title>聊天室</title>
    <!-- 自适配手机端尺寸 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />
    <style>
        .line {
            display: flex;
            justify-content: center;
            margin: 1rem;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .msg {
            display: flex;
            justify-content: flex-start;
            margin: 0.5rem;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .content {
            display: flex;
            flex-direction: column;
            width: 400px;
            border: solid 1px;
            padding: 1rem;
            overflow-x: scroll;
            max-height: 500px;
            overflow-y: auto;
            min-height: 100px;
        }

        .name {
            width: 35px;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .time {
            color: gray;
        }

        .info {
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: lightgray;
            padding: 1rem;
            border-radius: 1rem;
            opacity: 0.9;
        }
    </style>
</head>

<body>
<div class="line">
    <div class="content">
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好111111111111111111122222222222222222</div>
        </div>
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好</div>
        </div>
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好</div>
        </div>
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好</div>
        </div>
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好</div>
        </div>
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好</div>
        </div>
        <div class="msg">
            <div class="time">上午3:01:16</div>
            <div class="name">aaa</div>
            <div>:</div>
            <div>你好</div>
        </div>
    </div>
    <div>
        <div class="line">
            <div>用户名称</div>
            <input name="name" placeholder="请输入用户名" value="游客" />
        </div>
        <div class="line">
            <div>消息内容</div>
            <input name="message" placeholder="请输入内容" value="" />
        </div>
        <div class="line">
            <button>发送</button>
            <button>清屏</button>
        </div>
    </div>
</div>

<script>
    let serverUrl = 'http://localhost:9090';
    let wsUrl = 'ws://localhost:9090/chat';
    let ws;
    let wsErr = false;

    function doConnect() {
        let userId = elName.value; // 从输入框中获取 userId
        if (!userId) {
            showMsg({ message: '用户名称未填写，无法连接聊天室' });
            return;
        }
        ws = new WebSocket(`${wsUrl}?userId=${userId}`);

        ws.onclose = () => {
            if (!wsErr) {
                showMsg({ message: '聊天室已断开' });
                wsErr = true;
            }
            setTimeout(() => doConnect(), 2000); // 重连时也传递 userId
        };
        ws.onopen = () => {
            wsErr = false;
            showMsg({ message: '聊天室已连接' });
        };
        ws.onmessage = (event) => {
            let data = event.data;
            try {
                let msg = JSON.parse(data);
                showMsg(msg);
            } catch (err) {
                showMsg({ name: '系统', message: String(data) });
            }
        };
    }

    let elContent = document.getElementsByClassName('content').item(0);
    let elName = document.getElementsByName('name').item(0); // 修改为 elName
    let elMessage = document.getElementsByName('message').item(0);
    let btnSend = document.getElementsByTagName('button').item(0);
    let btnClear = document.getElementsByTagName('button').item(1);

    function getMsg() {
        let name = elName.value; // 修改为 elName
        let message = elMessage.value;
        return { name, message };
    }

    function showMsg(msg = { name: '', time: '', message: '' }) {
        let { name = '', time = Date.now(), message = '' } = msg;
        let timeStr;
        if (typeof (time) == 'number') {
            timeStr = new Date(time).toLocaleTimeString();
        } else {
            timeStr = new Date(String(time).substring(0, 19)).toLocaleTimeString();
        }
        let msgLine = document.createElement('div');
        msgLine.className = 'msg';
        msgLine.innerHTML = `<div class="name">${name}</div>
        <div class="time">${timeStr}</div>
        <div>${message}</div>`;
        elContent.insertBefore(msgLine, elContent.firstElementChild);
    }

    function info(msg = '') {
        let elInfo = document.createElement('div');
        elInfo.className = 'info';
        elInfo.innerHTML = `${msg}`;
        document.body.appendChild(elInfo);
        setTimeout(() => elInfo.remove(), 2000);
    }

    function sendMsg() {
        let { name, message } = getMsg();
        if (!name) {
            info('用户名称未填写');
            return;
        }
        if (!message) {
            info('消息内容未填写');
            return;
        }
        localStorage['name'] = name;
        elMessage.value = '';
        ws.send(JSON.stringify({ name, message }));
    }

    function clear() {
        elContent.innerHTML = '';
    }

    async function load() {
        let res = await fetch(serverUrl + "/ChatHistory/listHistory?pageNumber=1&pageSize=1000");
        let json = await res.json();
        window.json = json;
        console.log('json', json);
        if (json.data.records != null) {
            for (let i = 0; i < json.data.records.length; i++) {
                let his = json.data.records[i];
                showMsg(his);
            }
            json.data.records.forEach(his => showMsg(his));
        }
    }

    document.body.onload = async () => {
        btnSend.onclick = sendMsg;
        btnClear.onclick = clear;
        elName.value = localStorage['name'] || elName.value; // 修改为 elName
        clear();
        load();
        doConnect(); // 页面加载时初始化 WebSocket 连接
    };
</script>

</body>

</html>